package com.wms.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wms.bean.PageBean;
import com.wms.dto.*;
import com.wms.entity.StkLocation;
import com.wms.entity.StkWarehouse;
import com.wms.entity.TaskUser;
import com.wms.mapper.AddStkByGoodsMapper;
import com.wms.mapper.AddStkByLocationMapper;
import com.wms.service.AddStkByGoodsService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.HashSet;
import java.util.Set;

@Service
public class AddStkByGoodsServiceImpl implements AddStkByGoodsService {

    @Autowired
    AddStkByGoodsMapper mapper;

    @Autowired
    AddStkByLocationMapper addStkByLocationMapper;

    @Transactional(rollbackFor = Exception.class)
    public int addStkByGoods(AddStkByGoodsDTO task) {
        try {
            // 1. 参数校验（简化）
            if (task.getCodeList() == null || task.getCodeList().isEmpty() ||
                    task.getTaskName() == null || task.getStockId() == null || task.getTakeDate() == null) {
                return 0;
            }

            // 2. 保存主任务
            String maxCode = addStkByLocationMapper.getMaxCode();
            String newCode = null;
            if (maxCode != null && maxCode.startsWith("PD")) {
                String numberPart = maxCode.substring(2);
                int num = Integer.parseInt(numberPart) + 1;
                newCode = "PD" + String.format("%07d", num);
            }
            task.setCode(newCode);
            int result = mapper.addStkByGoods(task);
            if (result <= 0) return 0;
            
            // 从task对象中获取自增后的ID
            int taskId = task.getId();
            if (taskId <= 0) return 0;

            // 3. 遍历商品，插入明细和货位任务
            for (String code : task.getCodeList()) {
                // 3.1 插入明细并获取mid
                TaskDetailDTO detail = new TaskDetailDTO();
                detail.setTaskId(taskId);
                detail.setCode(code);
                if (mapper.insertStkByGoodsDetail(detail) <= 0 || detail.getMid() == 0) {
                    throw new RuntimeException("明细处理失败: " + code);
                }

                // 3.2 插入所有货位任务（只处理货位，不处理库区）
                for (WareAndLocDTO loc : mapper.getAreaLocNameByMid(detail.getMid())) {
                    // 添加空值检查，防止locationId为null
                    if (loc.getLocationId() == null || loc.getAreaId() == null) {
                        continue; // 跳过无效的货位数据
                    }
                    
                    StkLocation stkLoc = new StkLocation();
                    stkLoc.setTaskId(taskId);
                    stkLoc.setAreaId(loc.getAreaId());
                    stkLoc.setLocationId(loc.getLocationId());
                    stkLoc.setLocation(loc.getLocationName());
                    stkLoc.setTaskNum(mapper.setLocCount(loc.getLocationId(), code)); // 货位任务数
                    stkLoc.setFinishedNum(0);
                    addStkByLocationMapper.saveStkLocation(stkLoc);
                }
            }

            // 4. 最后统一统计并插入所有库区任务（一次性完成）
            mapper.saveSaveWareTask(taskId);

            return taskId;
        } catch (Exception e) {
            throw new RuntimeException("创建任务失败: " + e.getMessage());
        }
    }

    @Override
    public TaskUser queryUserByStoreId(int storeId) {

        try {
            TaskUser user = mapper.queryUserByStoreId(storeId);
            if (user.getStatus()==1){
                return user;
            }
        }catch (Exception e){
            throw new RuntimeException("查询用户失败: " + e.getMessage());
        }
        return null;
    }

    @Override
    public PageBean queryProductsByStoreId(int storeId, int page, int pageSize) {
        PageHelper.startPage(page, pageSize);
        List list = mapper.queryProductsByStoreId(storeId);
        PageInfo pageInfo = new PageInfo(list);
        return new PageBean(page, pageSize, pageInfo.getTotal(), list);
    }

    @Override
    public PageBean queryCommodityByStoreId(int storeId, int page, int pageSize) {
        PageHelper.startPage(page, pageSize);
        List list = mapper.queryCommodityByStoreId(storeId);
        PageInfo pageInfo = new PageInfo(list);
        return new PageBean(page, pageSize, pageInfo.getTotal(), list);
    }
}